const { User } = require('../models');
const { AppError } = require('../middlewares/errorHandler');
const { Op } = require('sequelize');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('../config');

class UserController {
  // 用户注册
  async register(ctx) {
    const { username, email, password, phone_number } = ctx.request.body;

    // 检查用户名是否已存在
    const existingUser = await User.findOne({
      where: {
        [Op.or]: [
          { username },
          { email },
          { phone_number }
        ]
      }
    });

    if (existingUser) {
      throw new AppError(400, '用户名、邮箱或手机号已被使用');
    }

    // 创建新用户
    const user = await User.create({
      username,
      email,
      password,
      phone_number,
      status: 'active',
      role: 'user'
    });

    ctx.body = {
      status: 'success',
      data: {
        user: {
          ...user.toJSON(),
          password: undefined
        }
      }
    };
  }

  // 用户登录
  async login(ctx) {
    const { username, password } = ctx.request.body;

    // 查找用户
    const user = await User.findOne({
      where: {
        [Op.or]: [
          { username },
          { email: username },
          { phone_number: username }
        ]
      }
    });

    if (!user || !(await bcrypt.compare(password, user.password))) {
      throw new AppError(401, '用户名或密码错误');
    }

    if (user.status !== 'active') {
      throw new AppError(403, '账户已被禁用');
    }

    // 生成 JWT token
    const token = jwt.sign(
      { id: user.id, role: user.role },
      config.jwt.secret,
      { expiresIn: config.jwt.expiresIn }
    );

    ctx.body = {
      status: 'success',
      data: {
        token,
        user: {
          ...user.toJSON(),
          password: undefined
        }
      }
    };
  }

  // 获取用户列表
  async getUsers(ctx) {
    const { page = 1, limit = 10, role, status } = ctx.query;
    const offset = (page - 1) * limit;

    const where = {};
    if (role) where.role = role;
    if (status) where.status = status;

    const { count, rows: users } = await User.findAndCountAll({
      where,
      limit: parseInt(limit),
      offset: parseInt(offset),
      attributes: { exclude: ['password'] }
    });

    ctx.body = {
      status: 'success',
      data: {
        total: count,
        users
      }
    };
  }

  // 获取单个用户
  async getUserById(ctx) {
    const { id } = ctx.params;
    const user = await User.findByPk(id, {
      attributes: { exclude: ['password'] }
    });

    if (!user) {
      throw new AppError(404, '用户不存在');
    }

    ctx.body = {
      status: 'success',
      data: {
        user
      }
    };
  }

  // 获取用户个人资料
  async getProfile(ctx) {
    const user = await User.findByPk(ctx.state.user.id, {
      attributes: { exclude: ['password'] }
    });

    ctx.body = {
      status: 'success',
      data: {
        user
      }
    };
  }

  // 更新用户个人资料
  async updateProfile(ctx) {
    const updateData = ctx.request.body;
    const user = await User.findByPk(ctx.state.user.id);

    // 检查邮箱和手机号是否已被其他用户使用
    if (updateData.email) {
      const existingUser = await User.findOne({
        where: {
          email: updateData.email,
          id: { [Op.ne]: ctx.state.user.id }
        }
      });
      if (existingUser) {
        throw new AppError(400, '该邮箱已被使用');
      }
    }

    if (updateData.phone_number) {
      const existingUser = await User.findOne({
        where: {
          phone_number: updateData.phone_number,
          id: { [Op.ne]: ctx.state.user.id }
        }
      });
      if (existingUser) {
        throw new AppError(400, '该手机号已被使用');
      }
    }

    // 不允许更新敏感字段
    delete updateData.password;
    delete updateData.role;
    delete updateData.status;

    await user.update(updateData);

    ctx.body = {
      status: 'success',
      data: {
        user: {
          ...user.toJSON(),
          password: undefined
        }
      }
    };
  }

  // 更新用户
  async updateUser(ctx) {
    const { id } = ctx.params;
    const updateData = ctx.request.body;

    const user = await User.findByPk(id);
    if (!user) {
      throw new AppError(404, '用户不存在');
    }

    // 检查邮箱和手机号是否已被其他用户使用
    if (updateData.email) {
      const existingUser = await User.findOne({
        where: {
          email: updateData.email,
          id: { [Op.ne]: id }
        }
      });
      if (existingUser) {
        throw new AppError(400, '该邮箱已被使用');
      }
    }

    if (updateData.phone_number) {
      const existingUser = await User.findOne({
        where: {
          phone_number: updateData.phone_number,
          id: { [Op.ne]: id }
        }
      });
      if (existingUser) {
        throw new AppError(400, '该手机号已被使用');
      }
    }

    // 如果更新密码，需要加密
    if (updateData.password) {
      updateData.password = await bcrypt.hash(updateData.password, 12);
    }

    await user.update(updateData);

    ctx.body = {
      status: 'success',
      data: {
        user: {
          ...user.toJSON(),
          password: undefined
        }
      }
    };
  }

  // 修改密码
  async changePassword(ctx) {
    const { currentPassword, newPassword } = ctx.request.body;
    const user = await User.findByPk(ctx.state.user.id);

    // 验证当前密码
    if (!(await bcrypt.compare(currentPassword, user.password))) {
      throw new AppError(401, '当前密码错误');
    }

    // 更新密码
    await user.update({
      password: await bcrypt.hash(newPassword, 12)
    });

    ctx.body = {
      status: 'success',
      data: null
    };
  }

  // 忘记密码
  async forgotPassword(ctx) {
    const { email } = ctx.request.body;
    const user = await User.findOne({ where: { email } });

    if (!user) {
      throw new AppError(404, '该邮箱未注册');
    }

    // TODO: 发送重置密码邮件
    // 这里需要集成邮件服务

    ctx.body = {
      status: 'success',
      message: '重置密码链接已发送到您的邮箱'
    };
  }

  // 重置密码
  async resetPassword(ctx) {
    const { token, newPassword } = ctx.request.body;

    // TODO: 验证重置密码token
    // 这里需要实现token验证逻辑

    ctx.body = {
      status: 'success',
      message: '密码重置成功'
    };
  }

  // 禁用用户
  async disableUser(ctx) {
    const { id } = ctx.params;
    const user = await User.findByPk(id);

    if (!user) {
      throw new AppError(404, '用户不存在');
    }

    await user.update({ status: 'disabled' });

    ctx.body = {
      status: 'success',
      data: null
    };
  }

  // 启用用户
  async enableUser(ctx) {
    const { id } = ctx.params;
    const user = await User.findByPk(id);

    if (!user) {
      throw new AppError(404, '用户不存在');
    }

    await user.update({ status: 'active' });

    ctx.body = {
      status: 'success',
      data: null
    };
  }

  // 删除用户
  async deleteUser(ctx) {
    const { id } = ctx.params;
    const user = await User.findByPk(id);

    if (!user) {
      throw new AppError(404, '用户不存在');
    }

    // 软删除用户
    await user.destroy();

    ctx.body = {
      status: 'success',
      data: null
    };
  }
}

module.exports = new UserController(); 